package top.tangyh.lamp.care.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.groovy.util.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.tangyh.basic.base.R;
import top.tangyh.basic.cache.redis2.RedisOps;
import top.tangyh.basic.interfaces.echo.EchoService;
import top.tangyh.basic.base.controller.SuperController;
import top.tangyh.lamp.care.entity.BDevBrandType;
import top.tangyh.lamp.care.entity.BEquipmentBrand;
import top.tangyh.lamp.care.entity.BPgpf;
import top.tangyh.lamp.care.service.BDevBrandTypeService;
import top.tangyh.lamp.care.service.BDevDetailService;
import top.tangyh.lamp.care.entity.BDevDetail;
import top.tangyh.lamp.care.service.BEquipmentBrandService;
import top.tangyh.lamp.care.vo.query.*;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.save.BDevDetailSaveVO;
import top.tangyh.lamp.care.vo.update.BDevDetailUpdateVO;
import top.tangyh.lamp.common.constant.CommonConstant;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

import static top.tangyh.lamp.common.constant.CommonConstant.BIND_IP_EQUIDENT;

/**
 * <p>
 * 前端控制器
 * 监护仪设备详情表
 * </p>
 *
 * @author zqb
 * @date 2024-07-15 16:42:41
 * @create [2024-07-15 16:42:41] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/device")
@Tag(name = "监护仪设备详情")
public class BDevDetailController  {
//    private final EchoService echoService;
//
//    @Override
//    public EchoService getEchoService() {
//        return echoService;
//    }


    private final RedisOps redisOps;

    private final BEquipmentBrandService bEquipmentBrandService;

    private final BDevBrandTypeService bDevBrandTypeService;


    private  final BDevDetailService bDevDetailService;


    /**
     * @Description:
     * @Param:
     * @return:
     * @Author: Mr.zqb
     * @Date: 2021/11/19
     */
    @Operation(summary = "新增设备")
    @PostMapping("save/devdetail")
    public R<Object> add(@RequestBody @Valid BDevDetail yxDevDetailPO) {
        //默认授权 false
        yxDevDetailPO.setIsAuthorize(1);
        boolean result = bDevDetailService.saveDevDetail(yxDevDetailPO);
        redisOps.set(CommonConstant.BIND_IP_EQUIDENT + yxDevDetailPO.getIp(), yxDevDetailPO.getDevCode());
        return R.success(result);
    }


    @Operation(summary = "更新设备信息")
    @PutMapping("update/devdetail")
    public R updateById(@RequestBody @Valid BDevDetail yxDevDetailPO) {
        boolean result = bDevDetailService.updateDevDetail(yxDevDetailPO);
        if (result) {
            //先删除旧的key的数据 再添加新的key对应的数据
            redisOps.del(BIND_IP_EQUIDENT + yxDevDetailPO.getIp());
            redisOps.set(BIND_IP_EQUIDENT + yxDevDetailPO.getIp(), yxDevDetailPO.getDevCode());
            return R.success();
        } else {
            return R.fail("更新失败");
        }
    }

    @Operation(summary = "分页查询设备信息")
    @PostMapping("/select/page/devices")
    public R<PageOutputDTO<DevDetailDto>> query(@RequestBody  DevDetailSearchVO query) {
        return R.success(bDevDetailService.queryPage(query));
    }

    @Operation(summary = "新增设备品牌信息")
    @PostMapping("save/brand")
    public R addBrand(@RequestBody @Valid BEquipmentBrand yxEquipmentBrandPO) {

        bEquipmentBrandService.save(yxEquipmentBrandPO);
        return R.success();
    }

    @Operation(summary = "更新设备品牌信息")
    @PutMapping("update/brand")
    public R updateByIdBrand(@RequestBody @Valid BEquipmentBrand yxEquipmentBrandPO) {
        bEquipmentBrandService.updateById(yxEquipmentBrandPO);
        return R.success();
    }

    @Operation(summary = "分页查询设备品牌信息")
    @PostMapping("/select/page/brand")
    public R<PageOutputDTO<EquipmentBrandDto>> query(@RequestBody @Valid EquipmentBrandSearchVO query) {
        return R.success(bEquipmentBrandService.queryPage(query));
    }

    @Operation(summary = "新增设备品牌型号")
    @PostMapping("save/brandType")
    public R<Object> addYxDevBrandType(@RequestBody @Valid BDevBrandType po) {
        BDevBrandType bDevBrandType = bDevBrandTypeService.save(po);
        return R.success(bDevBrandType.getId());
    }

    @Operation(summary = "更新设备品牌型号")
    @PostMapping("update/brandType")
    public R<Object> updateYxDevBrandType(@RequestBody @Valid BDevBrandType yxDevBrandTypePO) {
        return R.success(bDevBrandTypeService.updateById(yxDevBrandTypePO));
    }

    @Operation(summary = "分页查询设备品牌型号信息")
    @PostMapping("/select/page/brandType")
    public R<PageOutputDTO<DevBrandTypeDTO>> queryBrandTyp(@RequestBody  DevBrandTypeSearchVo yxDevBrandTypeSearchVo) {
        return R.success(bDevBrandTypeService.queryPage(yxDevBrandTypeSearchVo));
    }


//    @Operation(summary ="新增设备授权码信息")
//    @PostMapping("save/devAuth")
//    public R<Object> addDevAuth(  @RequestBody AddDevAuthDTO addDevAuthDTO) {
//
//        return R.success(yxDevAuthService.saveDevAuth(addDevAuthDTO));
//    }
//
//
//    @Operation(summary ="分页查询设备授权信息")
//    @GetMapping("/select/page/devauth")
//    public R<PageOutputDTO<DevAuthListVO>> queryDevAuth(DevAuthQueryVO devAuthQueryVO) {
//        return R.success(yxDevAuthService.queryPage(devAuthQueryVO));
//    }
//
//
//    @Operation(summary ="医院那边添加授权码")
//    @PostMapping("/update/devauth/status")
//    public R<Object> updateDevAuthStatus(String authcode) {
//        YxDevAuthPO one = yxDevAuthService.getDeveAuthByAuthCode(authcode);
//        if (null != one) {
//            return R.success(yxDevAuthService.updateStatusById(one, authcode));
//        }
//        return R.error("该授权码不存在!");
//    }
//
//    @Operation(summary ="授权码作废功能")
//    @PostMapping("/update/devauth/ivalid")
//    public R<Object> invalidDevAuthStatus(Long id) {
//
//        YxDevAuthPO po = new YxDevAuthPO();
//        po.setId(id);
//        po.setStatus("2");
//        return R.success(yxDevAuthService.updateById(po));
//    }


    /**
     * 批量添加管道管理配置
     */
    @PostMapping("save/brandAndBrandType")
    @Operation(summary = "批量添加品牌和对应的品牌型号信息")
    @Transactional(rollbackFor = Exception.class)
    public R<Object> savebrandAndBrandType(@RequestBody EquipmentBrandDto dto) {
        return R.success(bDevBrandTypeService.saveBrandAndBrandType(dto));
    }

    /**
     * 批量修改和新增品牌和对应的品牌型号信息
     */
    @PutMapping("/batch/brandAndbrandType")
    @Operation(summary = "批量修改和新增品牌和对应的品牌型号信息")
    @Transactional(rollbackFor = Exception.class)
    public R updateBrandAndBrandType(@RequestBody EquipmentBrandDto dto) {
        BEquipmentBrand po = BeanUtil.toBean(dto, BEquipmentBrand.class);
        // ConvertUtil.convert(dto, BEquipmentBrand.class);

        bDevBrandTypeService.updateBrandAndBrandType(dto, po);
        List list_del = dto.getListBrandTypeDel();
        if (null != list_del) {
            DeleteBactchQuery deleteBactchQuery=new DeleteBactchQuery();
            deleteBactchQuery.setIds(list_del);
            deleteBrandType(deleteBactchQuery);
        }
        return R.success();
    }


    @DeleteMapping("/brandType")
    @Operation(summary = "设备型号批量删除")
    public R deleteBrandType(@RequestBody DeleteBactchQuery deleteBactchQuery) {

//        List<BDevBrandType> list = new ArrayList<>();
        for (int i = 0; i < deleteBactchQuery.getIds().size(); i++) {
            BDevBrandType devBrandTypePO = new BDevBrandType();
            devBrandTypePO.setId(deleteBactchQuery.getIds().get(i));
            devBrandTypePO.setIsDeleted(1);
//            list.add(devBrandTypePO);
            bDevBrandTypeService.updateById(devBrandTypePO);
        }
        return R.success();
    }

    @DeleteMapping("/delete/batch")
    @Operation(summary = "设备批量删除")
    public R<Boolean> deleteDevDetail(@RequestBody DeleteBactchQuery deleteBactchQuery) {
        List<Long> ids=deleteBactchQuery.getIds();
        List<BDevDetail> list = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            BDevDetail po = new BDevDetail();
            po.setId(ids.get(i));
            po.setIsDeleted(1);

            BDevDetail po_wz = bDevDetailService.getById(ids.get(i));
            if(null==po_wz){
                return R.fail("该设备id" + ids.get(i) + "不存在");
            }
            int count = bDevDetailService.selectCountOfBindDev(po_wz.getDevCode());
            if (count > 0) {
                return R.fail("该设备标识：" + po_wz.getDevCode() + "已被绑定不能删除");
            }
            list.add(po);
//            superService.updateById(po);
        }
        boolean result = bDevDetailService.updateList(list);

        if (result) {
            for (int i = 0; i < ids.size(); i++) {
                BDevDetail po_all = bDevDetailService.getById(ids.get(i));
                //删除对应ip的缓存
                redisOps.del(BIND_IP_EQUIDENT + po_all.getIp());
            }
        }

        return R.success();
    }

    @DeleteMapping("/devBrand")
    @Operation(summary = "设备品牌批量删除")
    public R<Boolean> deletedevBrand(@RequestBody DeleteBactchQuery deleteBactchQuery ) {
        List<Long> ids=deleteBactchQuery.getIds();

        List<BEquipmentBrand> list = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            BEquipmentBrand po = new BEquipmentBrand();
            po.setId(ids.get(i));
            po.setIsDeleted(1);
            list.add(po);

            //删除该品牌下的型号
            bDevBrandTypeService.deleteByBrandId(ids.get(i));
        }
        return R.success(bEquipmentBrandService.updateList(list));
    }

    @Operation(summary = "下拉框模糊检索品牌")
    @GetMapping("/select/brand")
    public R<List<BEquipmentBrand>> getYxEquipmentBrandDtoList(String name) {

        QueryWrapper<BEquipmentBrand> wrapper = new QueryWrapper<>();
        wrapper.like("brand_code", name);
        List<BEquipmentBrand> list = bEquipmentBrandService.list(wrapper);

        return R.success(list);
    }

    @Operation(summary = "下拉框模糊检索设备标识")
    @GetMapping("/select/devCode")
    public R<List<String>> getdevCodeList(String devCode) {

        return R.success(bDevDetailService.getdevCodeList(devCode));
    }
}


